package com.cicc.springboot.service.impl;

import com.cicc.springboot.common.dto.R;
import com.cicc.springboot.entity.FileInfoEntity;
import com.cicc.springboot.mapper.FileInfoMapper;
import com.cicc.springboot.service.FileInfoService;
import com.cicc.springboot.utile.FileUploadUtil;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName FileInfoServiceImpl
 * @Description TODO
 * @Author 转轮王
 * @Date 2024/10/10 11:05
 * @Version 1.0
 */


@Service
public class FileInfoServiceImpl implements FileInfoService {

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    public R<String> uploadFiles(MultipartFile[] files, String attachmentId) {
        List<FileInfoEntity> fileInfoList;
        List<String> errorMessages = new ArrayList<>(); // 存储错误信息

        try {
            // 调用工具类保存文件并获取文件信息，同时收集错误信息
            fileInfoList = FileUploadUtil.saveFiles(files, errorMessages);

            // 遍历每个文件，将 attachmentId 关联到每个 FileInfoEntity
            for (FileInfoEntity fileInfo : fileInfoList) {
                fileInfo.setAttachmentId(attachmentId);
                fileInfoMapper.insert(fileInfo);
            }
            // 如果有错误信息，返回错误信息和成功上传的文件
            if (!errorMessages.isEmpty()) {
                return R.ok("部分文件上传成功，但有以下问题: " + String.join(", ", errorMessages));
            }
            return R.ok("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.failed("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("文件上传过程中发生错误: " + e.getMessage());
        }
    }


}


